const app = getApp();
const { SERVER_URL } = require('../../comm/script/config.js');

Page({
	data: {
		films: [],
		hasMore: true,
		showLoading: true,
		start: 0,
		count: 20,
		windowHeight: 0
	},

	onLoad: function() {
		var that = this;
		that.loadFilms();
	},

	onShow: function() {
		var that = this;
		try {
			const systemInfo = wx.getSystemInfoSync();
			that.setData({
				windowHeight: systemInfo.windowHeight
			});
		} catch (error) {
			console.error('获取窗口信息失败:', error);
			that.setData({
				windowHeight: 500 // 设置一个默认值
			});
		}
	},

	loadFilms: function() {
		var that = this;
		if (!that.data.hasMore) {
			return;
		}

		that.setData({ showLoading: true });

		wx.request({
			url: `${SERVER_URL}/api/coming-soon`,
			method: 'GET',
			data: {
				start: that.data.start,
				count: that.data.count
			},
			success: (res) => {
				if (res.statusCode === 200) {
					const newFilms = res.data.map(item => ({
						...item,
						images: { large: item.imageUrl || item.image_url || '' },
						rating: { average: parseFloat(item.average_rating) || 0, stars: (parseFloat(item.average_rating) * 5).toFixed(0) },
						genres: Array.isArray(item.genres) ? item.genres : (item.genres ? item.genres.split(',').map(genre => genre.trim()) : [])
					}));
					if (newFilms.length > 0) {
						that.setData({
							films: that.data.films.concat(newFilms),
							start: that.data.start + newFilms.length,
							hasMore: newFilms.length === that.data.count,
							showLoading: false
						});
					} else {
						that.setData({
							hasMore: false,
							showLoading: false
						});
					}
				} else {
					wx.showToast({
						title: res.data.message || '加载电影失败',
						icon: 'none'
					});
					that.setData({ showLoading: false });
				}
			},
			fail: (error) => {
				console.error('加载电影失败:', error);
				wx.showToast({
					title: '加载电影失败，请检查网络或服务器',
					icon: 'none'
				});
				that.setData({ showLoading: false });
			}
		});
	},

	scroll: function(e) {
		console.log(e);
	},

	scrolltolower: function() {
		var that = this;
		that.loadFilms();
	},

	onPullDownRefresh: function() {
		var that = this;
		that.setData({
			films: [],
			hasMore: true,
			showLoading: true,
			start: 0
		});
		that.loadFilms();
		wx.stopPullDownRefresh();
	},

	viewFilmDetail: function(e) {
		var id = e.detail.id;
		wx.navigateTo({
			url: "../filmDetail/filmDetail?id=" + id + "&type=coming_soon"
		});
	},

	viewFilmByTag: function(e) {
		var data = e.currentTarget.dataset;
		var keyword = data.tag;
		wx.navigateTo({
			url: '../searchResult/searchResult?url=' + encodeURIComponent(`${SERVER_URL}/api/search?tag=`) + keyword + '&keyword=' + keyword
		});
	}
});